<?php


namespace App\Transformer;


use App\Models\Customer;
use League\Fractal\TransformerAbstract;

class CustomerTransformer extends TransformerAbstract
{

    protected $defaultIncludes = ['createdUser', 'followUser'];

    public function transform(Customer $data)
    {
        $res = [
            'id' => $data->id,
            'contact_name' => $data->contact_name,
            'contact_mobile' => $data->contact_mobile,
            'company_name' => $data->company_name,
            'company_position' => $data->company_position,
            'create_id' => $data->create_id,
            'follow_id' => $data->follow_id,
            'wechat' => $data->wechat,
            'from' => $data->from,
            'from_text' => $data->getFromText(),
            'level' => $data->level,
            'level_text' => $data->getLevelText(),
            'province' => $data->province,
            'city' => $data->city,
            'district' => $data->district,
            'address' => $data->address,
            'assigned' => $data->assigned,
            'assigned_at' => $data->assigned_at ? $data->assigned_at->toDateTimeString() : '',
            'add_wechat_at' => $data->add_wechat_at ? $data->add_wechat_at->toDateTimeString() : '',
            'status' => $data->status,
            'status_text' => $data->getStatusText(),
            'remark' => $data->remark,
            'created_at' => $data->created_at->toDateTimeString(),
            'is_move' => isAdmin() || $data->follow_id == get_user_id()
        ];

        if ($data->relationLoaded('provinceData') && $data->provinceData) {
            $res['province_text'] = $data->provinceData->name;
        }

        if ($data->relationLoaded('cityData') && $data->cityData) {
            $res['city_text'] = $data->cityData->name;
        }

        if ($data->relationLoaded('districtData') && $data->districtData) {
            $res['district_text'] = $data->districtData->name;
        }

        return $res;
    }

    public function includeCreatedUser(Customer $data)
    {
        if ($data->relationLoaded('createdUser') && $data->createdUser) {
            return $this->item($data->createdUser, new UserTransformer());
        }
    }

    public function includeFollowUser(Customer $data)
    {
        if ($data->relationLoaded('followUser') && $data->followUser) {
            return $this->item($data->followUser, new UserTransformer());
        }
    }

}
